import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
// import 'package:sharesdk/sharesdk.dart';
import 'package:wanchong/api/user.dart';
import 'package:wanchong/bean/send_sms_response_entity.dart';
import 'package:wanchong/bean/success.dart';
import 'package:wanchong/intent/login.dart';
import 'package:wanchong/path.dart';
import 'package:wanchong/utils/common.dart';
import 'package:wanchong/utils/http.dart';
import 'package:wanchong/widget/app_bar.dart';
import 'package:fluttertoast/fluttertoast.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  bool loading = false;
  int value = 1;
  String prefer = "+ 86";
  var _scaffoldkey = new GlobalKey<ScaffoldState>();
  TextEditingController _controller = TextEditingController();
  bool _phoneTrue = false;
  bool _submit = false;
  @override
  void initState() {
    super.initState();
    print("Login init");
    // _controller.selection = ;
    // _controller = TextEditingController();
    // _controller.addListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      key: _scaffoldkey,
      appBar: MyAppBar(
          color: Colors.transparent,
          child: Align(
            alignment: Alignment.centerRight,
            child: GestureDetector(
              onTap: () {
                 Navigator.of(context).pushNamed(PloginPath);
              },
              child: Container(
                padding: EdgeInsets.only(right: 20.0),
                child: Text(
                  "密码登录",
                  style: TextStyle(color: Color(0xFF3C4450), fontSize: 15.0),
                ),
                // color: Colors.red,
              ),
            ),
          )),
      body: Container(
        margin: EdgeInsets.only(left: 46.0, right: 46.0),
        child: Column(
          children: <Widget>[
            Container(
              width: double.infinity,
              // color: Colors.red,
              margin: EdgeInsets.only(top: 48.0),
              child: Text(
                "免密登录",
                style: TextStyle(
                    fontSize: 28.0,
                    color: Color(0xFF3C4450),
                    fontWeight: FontWeight.w700),
              ),
            ),
            Container(
              width: double.infinity,
              margin: EdgeInsets.only(top: 10.0),
              child: Text(
                "您好，欢迎来到萌宠管家",
                style: TextStyle(
                  fontSize: 18.0,
                  color: Color(0xFF647280),
                ),
              ),
            ),
            // SizedBox(
            //   height: 46.0,
            // ),
            Container(
              margin: EdgeInsets.only(top: 46.0),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: TextField(
                      // maxLength: 11,
                      style:
                          TextStyle(color: Color(0xFF424D59), fontSize: 24.0),
                      controller: _controller,
                      keyboardType: TextInputType.phone,
                      decoration: InputDecoration(
                          contentPadding:
                              const EdgeInsets.symmetric(vertical: 4.0),
                          border: InputBorder.none,
                          hintText: "请输入手机号",
                          hintStyle: TextStyle(
                              color: Color(0xFFDBDBDB), fontSize: 18.0)),
                      onChanged: (text) {
                        //内容改变的回调
                        // print('change $text');
                        if (text.length > 11) {
                          text = text.substring(0, 11);
                          _controller.text = text;
                          _controller.selection = TextSelection.fromPosition(
                              TextPosition(
                                  affinity: TextAffinity.downstream,
                                  offset: text.length));
                        }
                        setState(() {
                          _submit = text.length == 11;
                        });
                      },
                    ),
                  )
                ],
              ),
            ),
            SizedBox(
              height: 16.0,
            ),
            Divider(
              color: Color(0xFFDDDDDD),
              height: 1.0,
            ),
            SizedBox(
              height: 20.0,
            ),
            GestureDetector(
              onTap: () {
                getSms();
              },
              child: ClipRRect(
                borderRadius: BorderRadius.circular(25.0),
                child: Container(
                  width: double.infinity,
                  height: 50.0,
                  color: _submit ? Color(0xFFFFCC33) : Color(0xFFFFE599),
                  child: Center(
                    child: Text(
                      "获取验证码",
                      style:
                          TextStyle(color: Color(0xFF313230), fontSize: 18.0),
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(
              height: 10.0,
            ),
            Text(
              "未注册手机验证后自动创建萌宠管家账号",
              style: TextStyle(fontSize: 12.0, color: Color(0xFFB4BEC6)),
            ),
            // SizedBox(height: 280.0,),
            Expanded(
              child: Container(),
            ),
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  _other("assets/login/login_icon_weixin.png", () {
                    _authToWx(context);
                  }),
                  _other("assets/login/login_icon_qq.png", () {}),
                  _other("assets/login/login_icon_weibo.png", () {}),
                ],
              ),
            ),
            SizedBox(
              height: 30.0,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text("登录即代表同意",
                    style: TextStyle(fontSize: 12.0, color: Color(0xFFB4BEC6))),
                GestureDetector(
                  onTap: () {},
                  child: Text(
                    "萌宠管家用户协议、隐私政策",
                    style: TextStyle(
                        fontSize: 12.0,
                        color: Color(0xFFFFCC33),
                        decoration: TextDecoration.underline),
                  ),
                )
              ],
            ),
            SizedBox(
              height: 50.0,
            )
          ],
        ),
      ),
    );
  }

  Widget _other(icon, call) {
    return GestureDetector(
      onTap: call,
      child: Container(
        width: 50.0,
        height: 50.0,
        child: Image.asset(icon),
      ),
    );
  }

  void _showPicker(context) {
    showBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                // leading: new Icon(Icons.photo_camera),
                title: Text("+ 86"),
                onTap: () {
                  setText("+ 86");
                  Navigator.pop(context);
                },
              ),
              new ListTile(
                // leading: new Icon(Icons.photo_camera),
                title: Text("+ 10"),
                onTap: () {
                  setText("+ 10");
                  Navigator.pop(context);
                },
              ),
              new ListTile(
                // leading: new Icon(Icons.photo_camera),
                title: Text("+ 12"),
                onTap: () {
                  setText("+ 12");
                  Navigator.pop(context);
                },
              ),
            ],
          );
        });
  }

  void setText(text) {
    setState(() {
      prefer = text;
    });
  }

  void getSms() {
    if (loading) return;
    loading = true;
    RegExp exp = RegExp(
        r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
    bool matched = exp.hasMatch(_controller.text);
    // print(matched);
    if (!matched) {
      Fluttertoast.showToast(
          msg: "手机号码格式不正确,请重新输入",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIos: 1,
          // backgroundColor: Colors.red,
          // textColor: Colors.white,
          fontSize: 16.0);
      loading = false;
      return;
    }
    sendSms(_controller.text).listen((SendSmsResponseEntity data) {
      loading = false;
      if (data.code == 200) {
        Fluttertoast.showToast(
            msg: "短信发送成功",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER);
        Future.delayed(Duration(seconds: 1), () {
          Navigator.of(context)
              .pushNamed(CheckPath, arguments: PhoneObj(_controller.text));
        });
      }
      // print(data);
    }).onError((err) {
      MyError e = err;
      loading = false;
      var msg = "";
      if (e.code == 300) {
        msg = e.message;
      } else {
        msg = "发送失败，请重试";
      }
      // print(err);
      alert(msg);
    });
  }

  void _authToWx(BuildContext context) {
    // ShareSDK.getUserInfo(ShareSDKPlatforms.wechatSession,
    //     (SSDKResponseState state, Map user, SSDKError error) {
    //   // alert(user != null ? user : error.rawData);
    //   print(user);
    // });
  }
}
